<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入角色名称" maxlength="10" />
      </el-form-item>
      <el-form-item label="角色头像" prop="avatar">
        <UploadImg v-model="formData.avatar" width="60px" height="60px" />
      </el-form-item>
      <el-form-item label="关联模型" prop="modelId" v-if="!isUserRole">
        <el-select
          v-model="formData.modelId"
          :empty-values="[0, '', null, undefined]"
          :value-on-clear="0"
          clearable
          placeholder="请选择关联模型"
        >
          <el-option
            v-for="model in modelList"
            :key="model.id"
            :label="model.platformName + ' - ' + model.name + (model.status === EnableStatusEnum.Disabled ? '（已禁用）' : '')"
            :value="model.id"
            :disabled="model.status === EnableStatusEnum.Disabled"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="角色类别" prop="category" v-if="!isUserRole">
        <el-input v-model="formData.category" placeholder="请输入角色类别" />
      </el-form-item>
      <el-form-item label="角色描述" prop="description">
        <el-input v-model="formData.description" type="textarea" placeholder="请输入角色描述" />
      </el-form-item>
      <el-form-item label="角色设定" prop="systemMessage">
        <el-input v-model="formData.systemMessage" type="textarea" :rows="10" placeholder="请输入角色设定" />
      </el-form-item>
      <el-form-item label="引用知识库" prop="knowledgeIds">
        <el-select v-model="formData.knowledgeIds" multiple clearable placeholder="请选择知识库">
          <el-option
            v-for="knowledge in knowledgeList"
            :key="knowledge.id"
            :label="knowledge.name + (knowledge.status === EnableStatusEnum.Disabled ? '（已禁用）' : '')"
            :value="knowledge.id"
            :disabled="knowledge.status === EnableStatusEnum.Disabled"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="引用工具" prop="toolIds">
        <el-select v-model="formData.toolIds" multiple clearable placeholder="请选择工具">
          <el-option
            v-for="tool in toolList"
            :key="tool.id"
            :label="tool.name + (tool.status === EnableStatusEnum.Disabled ? '（已禁用）' : '')"
            :value="tool.id"
            :disabled="tool.status === EnableStatusEnum.Disabled"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否公开" prop="publicStatus" v-if="!isUserRole">
        <el-radio-group v-model="formData.publicStatus">
          <el-radio v-for="dict in common_bool_type" :key="String(dict.value)" :value="dict.value">
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="排序" prop="sort" v-if="!isUserRole">
        <el-input-number v-model="formData.sort" controls-position="right" />
      </el-form-item>
      <el-form-item label="状态" prop="status" v-if="!isUserRole">
        <el-radio-group v-model="formData.status">
          <el-radio v-for="dict in common_enable_status" :key="dict.value" :value="dict.value">
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ChatRoleApi, ChatRoleVO } from '@/api/ai/model/chat_role'
import { ModelApi, ModelVO } from '@/api/ai/model/model'
import { KnowledgeApi, KnowledgeVO } from '@/api/ai/knowledge/knowledge'
import { ToolApi, ToolVO } from '@/api/ai/model/tool'
import { FormRules } from 'element-plus'
import { EnableStatusEnum } from '@/utils/constants'
import { AiModelTypeEnum } from '@/views/ai/utils/constants'

defineOptions({ name: 'AiChatRoleForm' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const { common_bool_type } = useBoolDict(DICT_TYPE.common_bool_type)
const { common_enable_status } = useIntDict(DICT_TYPE.common_enable_status)

const dialogVisible = ref(false) // dialog是否展示
const dialogTitle = ref('') // dialog标题
const formLoading = ref(false) // 表单加载中标记，1. 修改时的数据加载，2. 提交的按钮禁用
const formType = ref('') // 表单类型，新增：create，修改：update
const formDataObj = {
  id: undefined,
  modelId: undefined,
  name: undefined,
  avatar: undefined,
  category: undefined,
  description: undefined,
  systemMessage: undefined,
  knowledgeIds: undefined,
  toolIds: undefined,
  publicStatus: true,
  sort: 0,
  status: EnableStatusEnum.Enabled
}
const formData = ref({ ...formDataObj })
const formRules = reactive<FormRules>({
  name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
  avatar: [{ required: true, message: '角色头像不能为空', trigger: 'blur' }],
  category: [{ required: true, message: '角色类别不能为空', trigger: 'blur' }],
  description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }],
  systemMessage: [{ required: true, message: '角色设定不能为空', trigger: 'blur' }],
  publicStatus: [{ required: true, message: '是否公开不能为空', trigger: 'blur' }],
  sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const modelList = ref<ModelVO[]>([]) // 模型列表
const knowledgeList = ref<KnowledgeVO[]>([]) // 知识库列表
const toolList = ref<ToolVO[]>([]) // 工具列表

/** 是否【我】自己创建，私有角色 */
const isUserRole = computed(() => {
  return formType.value === 'my-create' || formType.value === 'my-update'
})

/** 打开弹窗 */
const open = async (type: string, id?: number, title?: string) => {
  dialogVisible.value = true
  dialogTitle.value = title || t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ChatRoleApi.getChatRole(id)
    } finally {
      formLoading.value = false
    }
  }
  modelList.value = await ModelApi.getModelSimpleList(AiModelTypeEnum.Chat)
  knowledgeList.value = await KnowledgeApi.getKnowledgeSimpleList()
  toolList.value = await ToolApi.getToolSimpleList()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const emit = defineEmits(['success']) // 定义success事件，用于操作成功后的回调
const submitForm = async () => {
  if (await formValidate(formRef)) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ChatRoleVO
    // tip: create、update 是后台管理调用
    // tip: my-create、my-update 是 chat 角色仓库调用
    if (formType.value === 'create') {
      await ChatRoleApi.createChatRole(data)
      message.success(t('common.createSuccess'))
    } else if (formType.value === 'update') {
      await ChatRoleApi.updateChatRole(data)
      message.success(t('common.updateSuccess'))
    } else if (formType.value === 'my-create') {
      await ChatRoleApi.createMy(data)
      message.success(t('common.createSuccess'))
    } else if (formType.value === 'my-update') {
      await ChatRoleApi.updateMy(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = { ...formDataObj }
  formRef.value?.resetFields()
}
</script>

<style scoped lang="scss"></style>
